package cc.htdf.gwc.datacompare.aspect;

import cc.htdf.gwc.datacompare.service.DateService;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import whisper.common.exception.sql.UniqueKeyException;
import whisper.common.utils.DateUtils;

import java.text.ParseException;

/**
 * Created by JT on 2017/10/12.
 */
@Component
@Aspect
public class DateCompareAspect {

    @Autowired
    private DateService dateService;

    @Pointcut(value = "execution(* cc.htdf.gwc.datacompare.service.DataCompareService.dataCompare(..)) && args(lastCompareDate)")
    void dataCompare(String lastCompareDate){}

    @AfterReturning(value = "dataCompare(lastCompareDate)")
    private void updateCompareDate(String lastCompareDate) throws ParseException {
        updateDate(lastCompareDate);
    }

    @AfterThrowing(value = "dataCompare(lastCompareDate)", throwing = "e")
    private void compareDataExceptionHandler(String lastCompareDate, Exception e) throws ParseException {
        if (e instanceof UniqueKeyException) {
            updateDate(lastCompareDate);
        }

    }

    private void updateDate(String lastCompareDate) throws ParseException {
        String nextDate = DateUtils.addHour(lastCompareDate, 1, "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss");
        dateService.updateLastCompareDate(nextDate);
    }


}
